<?php
namespace Home\Model;
use Think\Model;
class RevenueModel extends Model {
	protected $connection = array(
	'db_type'         => 'mysql',
	'db_user'         => 'root',
	'db_pwd'          => 'root',
	'db_host'         => 'localhost',
	'db_port'         => '3306',
	'db_name'         => 'test',
	'DB_FIELDS_CACHE' => false,
	'db_charset'      => 'utf8',
	);

	const STATE_1	=	1;//新导入数据
	
	const STATE_err =	-1;//错误的数据

	const STATE_Over =	2;//导入完成

	public function addNewData($data)
	{
		$data['csv_data_md5']=md5($data['csv_data']);
		if($this->checkRep($data['csv_data_md5']))
		{//已经存在相同数据
			$data['state']=self::STATE_err;
			$data['err_str']='已存在完全相同的数据';
		}
		else
		{
			$data['state']=self::STATE_1;
		}
		$data['add_time']=date("Y-m-d H:i:s");
		$state=$this->data($data)->add();
		if($state!=false)
		{
			$data['id']=$state;
			return $data;
		}
		else
			return false;
		//return 
	}


	public function checkRep($csv_data_md5)
	{
		$row=$this->where(array('csv_data_md5'=>$csv_data_md5,'state'=>array('neq',self::STATE_err)))->find();
		if(!empty($row)) return $row;
		else return false;
	}



	public function checkInsertData(&$data_row)
	{
		$data_row['state']=self::STATE_1;
		$data_row['add_time']=date("Y-m-d H:i:s");
		$data_row['csv_data_md5']=md5($data_row['csv_data']);
		if(empty($data_row['mssql_comid']))
		{
			$data_row['state']=self::STATE_err;
			$data_row['err_str']='未找到对应企业';
		}
	}



	public function getNewData($group_key,$limit=100)
	{
		$rows=$this->where(array('group_key'=>$group_key,'state'=>self::STATE_1))->limit($limit)->select();

		return $rows;
	}

/**
 * 导入完成状态更新
 * @param [type] $id [description]
 */
	public function setOver($id,$state=true,$err_str='数据导入失败')
	{
		if($state)
			$up_row=array('state'=>self::STATE_Over);
		else
			$up_row=array('state'=>self::STATE_err,'err_str'=>'数据导入失败');
		$this->where(array('id'=>$id))->save($up_row);
	}


	public function setAllOver($data_rows)
	{
		$all_sql='';
		foreach ($data_rows as $data_rows) {
			$all_sql.=$this->fetchSql(true)->where(array('state'=>self::STATE_1,'id'=>$data_rows['id']))->setField(state,self::STATE_Over).';';
		}
		
		$this->execute($all_sql);

	}

}